package bot;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;

import org.jibble.pircbot.PircBot;

public class LogBot extends PircBot {

	public LogBot() {
		super();
	}

	public void onMessage(String channel, String sender, String login,
			String hostname, String message) {
		super.onMessage(channel, sender, login, hostname, message);
		log(channel, sender, login, hostname, message);
	}

	public void onPrivateMessage(String sender, String login, String hostname,
			String message) {
		super.onPrivateMessage(sender, login, hostname, message);
		log(sender, sender, login, hostname, message);
	}
	
	@Override
	public void onJoin(String channel, String sender, String login, String hostname) {
		super.onJoin(channel, sender, login, hostname);
		String nick = sender;
		if(sender == this.getNick()) {
			nick = "You've";
		}
		log(channel, "System", login, hostname, nick+" joined the channel");
	}

	public void log(String channel, String sender, String login,
			String hostname, String message) {
		boolean append = true;
		BufferedWriter fw;
		try {
			String dirpath = System.getProperty("user.dir") + File.separator
					+ "logs";
			String filepath = dirpath + File.separator + channel + "-log.txt";
			File dir = new File(dirpath);
			dir.mkdirs();
			File f = new File(filepath);
			f.createNewFile();
			fw = new BufferedWriter(new FileWriter(f, append));
			fw.newLine();
			fw.write(Calendar.getInstance().getTime().toString() + "  "
					+ sender + " | " + message);
			fw.flush();
			fw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void log(String target, String message) {
		log(target, this.getNick(), this.getLogin(), this.getInetAddress().getHostName(), message);
	}
	
	public void sendMessage(String target, String message, boolean crap) {
		this.sendMessage(target, message);
		this.log(target, message);
	}
}
